﻿#include "musiclist.h"
#include <QMimeDatabase>

MusicList::MusicList()
{

}

iterator MusicList::begin()
{
    return musicList.begin();
}

iterator MusicList::end()
{
    return musicList.end();
}

iterator MusicList::findMusicById(const QString &musicid)
{
    for(iterator it=begin();it!=end();it++)
    {
        if(it->getMusicId()==musicid)
        {
            return it;
        }
    }
    return end();
}


void MusicList::addMusicByUrl(const QList<QUrl> &urls)
{
    for(auto musicUrl : urls)
    {
        QString musicPath=musicUrl.toLocalFile();
        if(musicPaths.contains(musicPath))
            continue;
        musicPaths.insert(musicPath);

        // 由于添加进来的⽂件不⼀定是歌曲⽂件，因此需要再次筛选出⾳乐⽂件
        QMimeDatabase minedb;
        QMimeType mimeTypy = minedb.mimeTypeForFile(musicPath);
        QString mime=mimeTypy.name();
        if(mime== "audio/mpeg" || mime== "audio/flac" || mime== "audio/wav")
        {
            Music music(musicUrl);
            musicList.push_back(music);
        }

    }
}

void MusicList::writeToDB()
{
    for(Music music : musicList)
    {
    // 让music对象将⾃⼰写⼊数据库
        music.insertMusicToDB();
    }
}

void MusicList::readMusicFromDb()
{
    QString sql("SELECT musicId, musicName, musicSinger, albumName,\
                duration, musicUrl, isLike, isHistory \
                FROM musicInfo");
    QSqlQuery query;
    if(!query.exec(sql))
    {
        qDebug()<<"数据库查询失败: "<<query.lastError().text();
        return;
    }

    while(query.next())
    {
        Music music;
        music.setMusicId(query.value(0).toString());
        music.setMusicName(query.value(1).toString());
        music.setSingerName(query.value(2).toString());
        music.setAlbumName(query.value(3).toString());
        music.setMusicUrl("file:///" + query.value(4).toString());
        music.setDuration(query.value(5).toLongLong());
        music.setIsLike(query.value(6).toBool());
        music.setIsHistory(query.value(7).toBool());
        musicList.push_back(music);

        musicPaths.insert(music.getMusicUrl().toLocalFile());
    }
}


